package com.ndp.fb.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ndp.fb.constant.CommonConstants;

import net.coobird.thumbnailator.Thumbnails;

/**
 * Created by infi.he on 2015/12/22.
 */
public class ImageUtil {
	private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);
    public static String getImageMd5(String url) {
        byte[] bytes = ArrayUtil.getByteByUrl(url);
        if (bytes != null) {
            return FileUtil.getFileMd5(bytes);
        }
        return null;
    }
    public static byte[] getThumbnail(String url) {
		URLConnection urlConnection = null;
		InputStream inputStream = null;
		File litImage = new File(com.ndp.fb.util.UUID.get() + ".jpg");
		try {
			URL httpUrl = new URL(url);
			urlConnection = httpUrl.openConnection();
			urlConnection.setConnectTimeout(CommonConstants.HTTP_CONNECTION_TIME_OUT);
			urlConnection.setReadTimeout(CommonConstants.HTTP_READ_TIME_OUT);
			inputStream = urlConnection.getInputStream();
			Thumbnails.of(inputStream).forceSize(100, 100).toFile(litImage);
			InputStream is = new FileInputStream(litImage);
			byte[] bytes = IOUtils.toByteArray(is);  
			is.close();
			return bytes;
		} catch (Exception e) {
			logger.error("获取图片缩略图出现异常>>>，url:{}",url);
			logger.error(e.getMessage(), e);
		} finally {
			if (null != inputStream) {
				IOUtils.closeQuietly(inputStream);
			}
			if (null != urlConnection) {
				IOUtils.close(urlConnection);
			}
			if (litImage != null) {
				litImage.delete();
			}
		}
		return null;
    }
}
